//
//  HMStatuesCell.swift
//  WeiBoSwift
//
//  Created by hgj on 2016/11/17.
//  Copyright © 2016年 HuGuoJian. All rights reserved.
//

import UIKit
import SDWebImage

private let margin: CGFloat = 8

//配图视图之间的间距
private let imageMargin: CGFloat = 2
private let maxWidth = ScreenWidth - 2 * margin
private let itemWidth = (maxWidth - 2 * imageMargin) / 3

class HMStatuesCell: UITableViewCell {

    //用户头像
    @IBOutlet weak var iconView: UIImageView!
    //用户名称
    @IBOutlet weak var nameLabel: UILabel!
    //用户等级
    @IBOutlet weak var mbRankView: UIImageView!
    //微博时间
    @IBOutlet weak var timeLabel: UILabel!
    //微博来源
    @IBOutlet weak var sourceLabel: UILabel!
    //微博正文
    @IBOutlet weak var contentLabel: YYLabel!
    //微博用户认证类型
    @IBOutlet weak var avatarView: UIImageView!
    //配图视图
    @IBOutlet weak var pictureView: HMPictureView!
    
    @IBOutlet weak var pictureHeightCons: NSLayoutConstraint!
    
    @IBOutlet weak var pictureWidthCons: NSLayoutConstraint!
    
    //关联配图视图的布局对象
    @IBOutlet weak var pictureViewFlowLayout: UICollectionViewFlowLayout!
    
    @IBOutlet weak var retweetedLabel: YYLabel!
    
    @IBOutlet weak var toolBar: UIView!
    
    //配图视图顶部约束对象
    @IBOutlet weak var pictureViewTopCons: NSLayoutConstraint!
    
    
    var viewModel: HMStatusesViewModel? {
        didSet {
            iconView.sd_setImage(with: viewModel?.iconURl, placeholderImage: #imageLiteral(resourceName: "avatar_default_small"))
            
            nameLabel.text = viewModel?.statues?.user?.name
            
            mbRankView.image = viewModel?.mbRankImage
            
//            timeLabel.text = viewModel?.statues?.created_at
            timeLabel.text = viewModel?.timeText

            
//            sourceLabel.text = viewModel?.statues?.source
            sourceLabel.text = viewModel?.sourceText
            
//            contentLabel.text = viewModel?.statues?.text
            contentLabel.attributedText = viewModel?.originAttributedString
            
            avatarView.image = viewModel?.verifitedImage
            
            
            pictureView.pictureInfos = viewModel?.statues?.pic_urls
            
            // 数量 和 尺寸
//            let count = viewModel?.statues?.pic_urls?.count ?? 0
            let count = viewModel?.imageURLs?.count ?? 0
            
            //根据count值 修改顶部约束对象的值  =========>>???
            pictureViewTopCons.constant = (count == 0 ? 0 : margin)
            
            let result = calculatePictureVieSize(count: count)
            
            // 宽高约束
            pictureWidthCons.constant = result.pSize.width
            pictureHeightCons.constant = result.pSize.height
            
            //还需要更新itemSize 会出现复用的问题
            pictureViewFlowLayout.itemSize = result.itemSize
            
            //给配图视图设置数据源 设置转发微博的配图视图的数据
            //转发微博和原创微博都是公用了配图视图
            pictureView.pictureInfos = viewModel?.imageURLs
            
            //8.1  不会立即更行约束,配图视图的大小还是使用的上一个cell的尺寸
            pictureView.layoutIfNeeded()

            
            //设置配图视图的文本
            /*
             if viewmodel?.status?.retweeted_status != nil {
             retweetedLabel.text = viewmodel?.status?.retweeted_status?.text
             }
             */
//            retweetedLabel?.text = viewModel?.statues?.retweeted_status?.text
            retweetedLabel?.attributedText = viewModel?.retweetedAttributedString
            
            
            contentLabel.highlightTapAction = { (containerView,text,range,rect) -> () in
                //containerView,就是被点击的视图
                //text: 被点击的属性文本
                //range: 点击的特殊文本 范围
                //rect: 点击的特殊的文本的坐标
                let sub = (text.string as NSString).substring(with: range)
                print(sub)
                //跳转页面   响应者链条来实现页面跳转
                if sub.hasPrefix("http") {
                    let web = HMWebViewController()
                    web.urlString = sub
                    self.findNavController()?.pushViewController(web, animated: true)
                }
            }

            retweetedLabel?.highlightTapAction = { (containerView,text,range,rect) -> () in
                //containerView,就是被点击的视图
                //text: 被点击的属性文本
                //range: 点击的特殊文本 范围
                //rect: 点击的特殊的文本的坐标
                let sub = (text.string as NSString).substring(with: range)
//                print(sub)
                //跳转页面   响应者链条来实现页面跳转
                
                if sub.hasPrefix("http") {
                    let web = HMWebViewController()
                    web.urlString = sub
                    self.findNavController()?.pushViewController(web, animated: true)
                }
            }
        }
    }
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        // 背景色 随机色
//        contentView.backgroundColor = randomColor()
        
        // 设置内容
        contentLabel.numberOfLines = 0
        contentLabel.preferredMaxLayoutWidth = ScreenWidth - margin * 2
        
        // 注意 retweetedLabel + ?  可能为nil
        retweetedLabel?.numberOfLines = 0
        retweetedLabel?.preferredMaxLayoutWidth = ScreenWidth - margin * 2
        
        // 设置layout
        pictureViewFlowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        pictureViewFlowLayout.minimumLineSpacing = imageMargin
        pictureViewFlowLayout.minimumInteritemSpacing = imageMargin
        
         contentLabel.font = UIFont.systemFont(ofSize: 15)
        // 设置选中样式
        selectionStyle = .none
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
    // 根据图片的张数计算配图视图的大小,更新配图视图的宽高约束对象的值
    private func calculatePictureVieSize(count: Int) -> (pSize: CGSize,itemSize: CGSize) {
        
        if count == 0 {
            return (CGSize(width: 1, height: 1),CGSize(width: 1, height: 1))
        }
        
        if count == 1 {
            //计算图片的大小  获取图片  -> image.size  必须确保在这里一定能够获取到图片
            //不能够在这个地方下载图片 否则会执行多次刷新(有多少个单张图片就需要刷新多少次)
            if let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: viewModel?.imageURLs?.last?.wap360 ?? "") {
                let imageSize = image.size
                //不能再if中单独设置itemSize
                //pictureViewFlowLayout.itemSize = imageSize
                return (imageSize,imageSize)
            }
            
            return (CGSize(width: itemWidth, height: itemWidth),CGSize(width: itemWidth, height: itemWidth))
        }
        
        if count == 4 {
            let width = 2 * itemWidth + imageMargin
            return (CGSize(width: width, height: width),CGSize(width: itemWidth, height: itemWidth))
        }
        
        // row col
        let row = CGFloat(count / (3 + 1)) + 1
        let h = row * itemWidth + (row - 1) * imageMargin
        return (CGSize(width: maxWidth, height: h),CGSize(width: itemWidth, height: itemWidth))
    }
}

